package com.lmf.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.netflix.zuul.filters.route.FallbackProvider;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.stereotype.Component;


import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
@Component
public class ZuulFallbackProviders implements FallbackProvider {
    public Logger logger= LoggerFactory.getLogger(ZuulFallbackProviders.class);
    //指明熔断拦截那个服务，如果"*" 代表所有的路由服务都要添加熔断功能
    //注意别填路由名称,要填对应的服务,否则就会找不到
    @Override
    public String getRoute() {
        return "colony-test";
    }
    //当这个路由出现异常,熔断进行相关操作
    @Override
    public ClientHttpResponse fallbackResponse(String route, Throwable cause) {
        logger.info("---Excption {}",cause.getCause().getMessage());
        System.out.println("我已经达到熔断器了");
        if(cause!=null && cause.getCause()!=null){
            String reason=cause.getCause().getMessage();
            logger.info("Exeption {}",reason);
        }
        return new ClientHttpResponse() {
            @Override
            public HttpStatus getStatusCode() throws IOException {
                return HttpStatus.OK;
            }

            @Override
            public int getRawStatusCode() throws IOException {
                //返回对应状态的值就可以了
                return HttpStatus.NOT_FOUND.value(); //默认是为0 如果是0的将不会输出任何东西
            }

            @Override
            public String getStatusText() throws IOException {
               // return  HttpStatus.NOT_FOUND.getReasonPhrase();
                return "ok";
            }

            @Override
            public void close() {

            }

            @Override
            public InputStream getBody() throws IOException {
                String s="error";
                System.out.println(s.getBytes());
                return new ByteArrayInputStream(s.getBytes());
            }

            @Override
            public HttpHeaders getHeaders() {
                HttpHeaders httpHeaders=new HttpHeaders();
                httpHeaders.setContentType(MediaType.APPLICATION_JSON);
                return httpHeaders;
            }
        };
    }


}
